<?php
declare (strict_types = 1);

namespace app\adminapi\service;

use app\adminapi\model\system\auth\AdminSession;
use app\common\cache\AdminTokenCache;
use think\facade\Config;
class AdminTokenService
{

    public static function setToken(int $adminId ,int $terminal , $multipointLogin = 1 )
    {
        $time = time();

        $adminSession = AdminSession::where([
            ['admin_id' , '=' , $adminId],
            ['terminal' ,'=' , $terminal]
        ])->find();
        $expireTime = $time + Config::get('adminmatrix.admin_token.expire_duration');

        $adminTokenCache = new AdminTokenCache();

        if ($adminSession)
        {
            if ($adminSession->expire_time < $time || $multipointLogin === 0) {
                //清空缓存
                $adminTokenCache->deleteAdminInfo($adminSession->token);
                //如果token过期或账号设置不支持多处登录，更新token
                $adminSession->token = create_token($adminId);
            }
            $adminSession->expire_time = $expireTime;
            $adminSession->update_time = $time;

            $adminSession->save();

        } else{
            $adminSession = AdminSession::create([
                'admin_id' => $adminId,
                'terminal' => $terminal,
                'token' => create_token($adminId),
                'expire_time' => $expireTime

            ]);
        }

        return $adminTokenCache->setAdminInfo($adminSession['token']);
    }
    public static function overtimeToken($token) : array |bool
    {
        $time = time();
        $adminSession = (new AdminSession) -> where('token', '=', $token)->findOrEmpty();
        if ($adminSession->isEmpty()) {
            return false;
        }
        //延长token过期时间
        $adminSession->expire_time = $time + Config::get('project.admin_token.expire_duration');
        $adminSession->update_time = $time;
        $adminSession->save();
        return (new AdminTokenCache())->setAdminInfo($adminSession->token);
    }


    public static function expireToken($token)
    {

        $adminSession = (new AdminSession) ->where('token', '=', $token)
            ->with('adminapi')
            ->findOrEmpty();

        if ($adminSession->isEmpty()) {
            return false;
        }

        //当支持多处登录的时候，服务端不注销
        if ($adminSession->admin->multipoint_login === 1) {
            return false;
        }

        $time = time();
        $adminSession->expire_time = $time;
        $adminSession->update_time = $time;
        $adminSession->save();
        return (new AdminTokenCache())->deleteAdminInfo($token);
    }

}

